package cc.chengheng.service;

import cc.chengheng.dao.UserDao;
import cc.chengheng.model.UserDto;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service
public class SpringUserDetailsService implements UserDetailsService {

    @Resource
    UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("用户名" + username);

        UserDto userDto = userDao.getUserByUsername(username);

        if (userDto == null) { // 查不到信息返回null，由provider来抛出异常
            return null;
        }

        List<String> permissionsByUserId = userDao.findPermissionsByUserId(userDto.getId());
        return User.withUsername(userDto.getUsername())
                .password(userDto.getPassword())
                .authorities(permissionsByUserId.toArray(new String[permissionsByUserId.size()]))
                .build();
    }
}
